package l.l.w.CodingInterviews;

import org.junit.Test;

import java.util.Arrays;

/**
 * Created by llw on 2018/3/1.
 */
public class _05Problem {

    @Test
    public void test1(){
        int [] a1={1,3,4,5,7,9,0,0,0,0,0,0,0,0};
        int [] a2={1,2,4,6,8,10};
        new _05Problem().combine(a1,6,a2);
        System.out.println(Arrays.toString(a1));

//        StringBuffer sb = new StringBuffer();
//        sb.ins
//        sb.charAt(0);
//        sb.length();
//        sb.setCharAt(0,'1');
//        sb.s
    }

    /**
     * 题目描述：
     *      有两个排好序的数组A1和A2，A1后有额外的长度，足够容纳A2，请事先一个函数，把A2中的所有数组插入A1中，并且所有的数字是排序的。
     * @param a1
     * @param asize
     * @param a2
     */
    public void combine(int[] a1,int asize, int[] a2){
        int bsize = a2.length;
        if(a1==null || a2==null ||a1.length < asize+bsize) return;
        int k = asize + bsize - 1;
        int i = asize-1,j = bsize-1;
        for(; i>= 0 && j >= 0;){
            if(a1[i] > a2[j])
                a1[k--] = a1[i--];
            else a1[k--] = a2[j--];
        }
        if(j>=0){
            while(j >= 0){
                a1[k--] = a2[j--];
            }
        }
    }
    @Test
    public void test2(){
        StringBuffer sb = new StringBuffer("Hello World");
        String result = new _05Problem().replaceSpace(sb);
        System.out.println(result);
    }
    public String replaceSpace(StringBuffer str) {
        int spaceCount = 0;
        int i = 0;
        for(; i < str.length();++i){
            char cur = str.charAt(i);
            if(cur == ' ') spaceCount++;
        }
        int len = i + 2 * spaceCount-1;
        for(int k=0; k < 2 * spaceCount; ++k){
            str.insert(i+k,'1');
        }
        while(i>0 && spaceCount>0){
            char cur = str.charAt(i-1);
            if(cur == ' '){
                str.setCharAt(len--,'0');
                str.setCharAt(len--,'2');
                str.setCharAt(len--,'%');
                i--;
                spaceCount--;
            }else{
                str.setCharAt(len--,cur);
                i--;
            }
        }
        return str.toString();
    }
}
